package com.muyi.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 封装BaseDaoImpl
 */
public class BaseDaoImpl {

    /**
     * 增删改的通用方法
     * @param sql
     * @param params
     * @return
     * @throws Exception
     */
    public int cudMethod(String sql,Object... params) throws Exception {
        //获取数据库连接
        Connection connection = JDBCUtils.getConnection();
        //获取数据库语句的执行对象
        PreparedStatement statement = connection.prepareStatement(sql);
        //给？赋值
        if (null != params){
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i+1,params[i]);
            }
        }
        //执行sql语句
        int i = statement.executeUpdate();
        //释放资源
        JDBCUtils.close(null,statement,connection);
        return i;
    }

    public <T> List<T> queryMethod(String sql,Class<T> c ,Object... params) throws Exception {
        //获取数据库连接对象
        Connection connection = JDBCUtils.getConnection();
        //获取数据库语句的执行对象
        PreparedStatement statement = connection.prepareStatement(sql);
        //给？赋值
        if (null != params){
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i+1,params[i]);
            }
        }
        //执行sql语句
        ResultSet resultSet = statement.executeQuery();

        //获取元数据信息
        ResultSetMetaData metaData = resultSet.getMetaData();
        int count = metaData.getColumnCount();

        List<T> list = new ArrayList<>();
        //解析resultset结果集
         while (resultSet.next()){
             //创建T泛型对象
             T t = c.getConstructor().newInstance();
             for (int i = 1; i <= count; i++) {
                 //取出第i列的名称
                 String columnName = metaData.getColumnLabel(i);
                 //根据列名获取对应的值
                 Object value = resultSet.getObject(columnName);

                 //反射给返回值对象赋值
                 Field field = c.getDeclaredField(columnName);
                 field.setAccessible(true);
                 if (null != value) {
                     field.set(t,value);
                 }
             }
             list.add(t);
         }
        //释放资源
        JDBCUtils.close(resultSet,statement,connection);
         //返回数据
        return list;
    }
}
